﻿using System;
using System.Collections.Generic;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Flagwind.Externals.Json.Converters
{
    public class ObjectConverter : JsonConverter
    {
        #region 重写方法

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(object);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            switch(reader.TokenType)
            {
                case JsonToken.StartArray:
                    var array = (JArray)JArray.ReadFrom(reader);
                    var result = new Dictionary<string, object>[array.Count];

                    for(int i = 0; i < result.Length; i++)
                        result[i] = array[i].ToObject<Dictionary<string, object>>();

                    return result;
                case JsonToken.StartObject:
                    var obj = JObject.ReadFrom(reader);
                    return obj.ToObject<Dictionary<string, object>>();

                //Tip:以下代码或许可以递归激发该类型转换的解析
                //return serializer.Deserialize<Dictionary<string, object>>(reader);
                case JsonToken.Null:
                case JsonToken.Undefined:
                    return null;
                default:
                    return reader.Value;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}
